﻿-- LootDecider object which several methods can be called globally
DKPMSld = {}

isAcceptingBids = false;

debugging = false;



BidsReceived = {};

StaticPopupDialogs["GiveLoot_WARNING"] = {
	text = "%s\r\n to\r\n %s",
	button1 = YES,
	button2 = NO,
	OnAccept = function(self) 

		GiveMasterLoot(self.data[1],self.data[2]);
		DKPMS:Print(self.data[1].."-"..self.data[2])
		getglobal("LootDeciderGiveLoot"):Disable();
		getglobal("LootDecider"):Hide();		
	end,
	timeout = 0,
	whileDead = 1,
	hideOnEscape = 1,
};


function DKPMSld:InitializeLootDecider()
   SLASH_LOOTDECIDER1 = "/lootdecider";
   SLASH_LOOTDECIDER2 = "/ld";
   SLASH_LOOTDECIDER3 = "/loot";
   SlashCmdList["LOOTDECIDER"] = function(msg)
		DKPMSld:LootDecider_SlashCommandHandler(msg);
   end
   local frame = getglobal("LootDecider")
   if(frame) then
	   tinsert(UISpecialFrames, frame)	  
   end	
end

 
function DKPMSld:LootDecider_SlashCommandHandler(msg)    

   local found = string.find(msg, "^|c%x+|H(.+)|h%[.+%]")
   if(found ~= nil) then
	  DKPMSld:LootDecider_Toggle(msg);
   end
	
end
 
function DKPMSld:LootDecider_Toggle(msg)
   local frame = getglobal("LootDecider")
   if (frame) then
      if(  frame:IsVisible() ) then
	for i = 1, 6 do
		getglobal("RowEntry"..i.."StartButton"):Enable();
	end

         frame:Hide();

      else
		ItemLinkText:SetText(msg)
		 frame:Show();
      end
   end
end


function DKPMSld:LootDecider_OnClickStart(arg1)
	BidsReceived = {}; 
	isAcceptingBids = true;				
	DKPMSld:BlindBid_Start();
end

function DKPMSld:LootDecider_OnClickStop(arg1)
	isAcceptingBids = false;

	SendChatMessage("Bidding closed on "..ItemLinkText:GetText(), "RAID", nil, nil);


	LootDeciderStopTimer:Disable();
	LootDeciderStartTimer:Enable();
	LootDeciderAccept:Disable();

	LootDeciderPlayer:SetText("");
	LootDeciderAmount:SetText("");


	for i = 1, 6 do
		getglobal("RowEntry"..i.."StartButton"):Enable();
	end
end

function DKPMSld:LootDecider_OnClickClose()
	if(isAcceptingBids==true) then
		DKPMSld:LootDecider_OnClickStop(arg1); --stop bidding
	end

   DKPMSld:LootDecider_Toggle(); 
end

function DKPMSld:LootDecider_OnClickAccept(arg1)
	if(isAcceptingBids) then   

			isAcceptingBids = false;

			DKPMSld:BlindBid_End();

	end
end

function DKPMSld:LootDecider_onEvent()	
	if(zKP_raid_running) then --only show is raid is running
		if(isAcceptingBids and (strsub(event, 1, 13) == "CHAT_MSG_RAID" or strsub(event, 1, 20) == "CHAT_MSG_RAID_LEADER") ) then
		
			DKPMSld:BlindBid_Event(arg1, arg2); --arg1 = message  arg2 = sender
				
		end

		if( event == "LOOT_OPENED" ) then
		local lootmethod, masterlooterID = GetLootMethod();

			if(lootmethod=="master" and masterlooterID==0) then -- if its masterloot and you are ML, ta bort -- sen
			local real_index = 1;


			   for index = 1, 6, 1 do
				getglobal("RowEntry"..index):Hide();
				getglobal("RowEntry"..index.."StartButtonText"):SetText("Open");
			   end

			local counter = 0;
	
			   for index = 1, GetNumLootItems(), 1 do
				local lootIcon, lootName, lootQuantity, rarity= GetLootSlotInfo(index);
				 if (LootSlotIsItem(index) and rarity>=3) then --ändra till 3 sen

				 counter = counter+1;

				button = getglobal("RowEntry"..real_index);

				local texture, item, quantity, quality = GetLootSlotInfo(index);

				color = ITEM_QUALITY_COLORS[quality];

				getglobal("RowEntry"..real_index.."IconTexture"):SetTexture(texture);
				getglobal("RowEntry"..real_index.."Text"):SetText(item);
				getglobal("RowEntry"..real_index.."Text"):SetVertexColor(color.r, color.g, color.b);

				getglobal("RowEntry"..real_index.."TooltipID"):SetText(GetLootSlotLink(index));
				getglobal("RowEntry"..real_index.."LootID"):SetText(index);

					button:Show();

				real_index = real_index+1;
				 end
			   end
				if(counter>0) then
					zLootWindow:Show();
				end
			end 
		end

	end 
end


function DKPMSld:PairsByKeys (t, f)
  local a = {}
  -- build temporary table of the keys
  for n in pairs (t) do 
    table.insert (a, n) 
  end
  table.sort (a, f)  -- sort using supplied function, if any
  local i = 0        -- iterator variable
  return function () -- iterator function
    i = i + 1
    return a[i], t[a[i]]
  end  -- iterator function
end 

function DKPMSld:BlindBid_Start()

	local send_msg = ItemLinkText:GetText().." up for bids";

	if (IsRaidOfficer()) then --weither we are Assistant or else
		SendChatMessage(send_msg, "RAID_WARNING", nil, nil); 
	else
		SendChatMessage(send_msg, "RAID", nil, nil);
	end
end

function DKPMSld:BlindBid_Event(message, sender)
	local bidtaken;
	local whichplayer = sender;
	local lowerCaseMessage = string.lower(message);

	   local biggest = 0;
	   local whosebiggest = 0;
       if(LootDeciderAmount:GetText() ~= "") then
        whosebiggest = tonumber( LootDeciderAmount:GetText() );
       end

	_, _, bidtaken = string.find(lowerCaseMessage, "^bid (%d+)$");			
    
    if( _ == nil) then
	else				
		if(tonumber(bidtaken) <= 0) then
			SendChatMessage("<zKP> You must bid a higher then zero.", WHISPER, nil, sender);
		elseif (tonumber(bidtaken) > whosebiggest) then
                local classOfSender = UnitClass(sender);
                
                if(classOfSender == "Death Knight") then --If the class is a death knight then the string used to retrieve the checkbox element is concatenated into the correct name.
                    classOfSender = "Death_Knight";
                end
                
                local class_chkbox = getglobal( classOfSender .. "_chkbox");
                
                --Check if its an Alt of someone
                if(AltList[whichplayer]) then
                    --If it is an alt, be sure to add to the main of that alt
                    whichplayer = AltList[whichplayer];
                end					

                if(class_chkbox:GetChecked() == 1) then
                    if(DKPMS:GetPlayerDKP(whichplayer) <= tonumber(bidtaken) ) then
                        bidtaken = DKPMS:GetPlayerDKP(whichplayer);
                        SendChatMessage("<zKP>"..sender.."'s bid changed to "..bidtaken.." DKP","RAID",nil,nil);
		                end
                        if(BidsReceived[ sender ]) then
                            if(tonumber(BidsReceived[ sender ]) < tonumber(bidtaken)) then --accept only if bid is bigger
                                    BidsReceived[ sender ] = bidtaken;
                            end
                        else
                            BidsReceived[ sender ] = bidtaken;
                        end
                        
                        for a_name,a_bid in pairs(BidsReceived) do
                        
                            if(tonumber(a_bid) > biggest) then
                                whosebiggest = a_name;
                                biggest = tonumber(a_bid);
                            end
                        end
    
    
                        if(tonumber(DKPMS:GetPlayerAttendance(whichplayer))<tonumber(zKP_options.bid_attendance_percent)) then
                            SendChatMessage("<zKP>Your bid has been accepted. But beware, your attendance is below "..zKP_options.bid_attendance_percent.."% so your bid might not count.", WHISPER, nil, sender);
                        else
                            SendChatMessage("<zKP>Your bid has been accepted.", WHISPER, nil, sender);
                        end
                        
                        LootDeciderPlayer:SetText(whosebiggest);
                        LootDeciderAmount:SetText(biggest);
                            
                    if(tonumber(DKPMS:GetPlayerAttendance(whichplayer))<tonumber(zKP_options.bid_attendance_percent)) then
                        SendChatMessage("* Warning: "..whichplayer.." has below "..zKP_options.bid_attendance_percent.."% attendance *", "RAID", nil, nil);
                        DEFAULT_CHAT_FRAME:AddMessage("* Warning: "..whichplayer.." has below "..zKP_options.bid_attendance_percent.."% attendance *");
                    end
    
                else
                    SendChatMessage("<zKP>Your class is not allowed to bid on this item.", WHISPER, nil, sender);
                end				
            else
                difference = (whosebiggest-tonumber(bidtaken));
                if (difference <= 0) then
                    SendChatMessage("<zKP>You have to bid higher then "..whosebiggest.." DKP to participate in the bidding.",WHISPER,nil,sender);
                else
                    SendChatMessage("<zKP>Your current bid of "..bidtaken.." is "..difference.." lower then highest bid.",WHISPER,nil,sender);
                end
               
		end
	end
end

function DKPMSld:BlindBid_End()
   local biggest = 0;
   local whosebiggest = "";
   
   for name,bid in pairs(BidsReceived) do
   
	if(tonumber(bid) > biggest) then
		 whosebiggest = name;
		 biggest = tonumber(bid);
	  end
   end

	if(biggest == 0) then
		if(LootDeciderPlayer:GetText()~="" and LootDeciderAmount:GetText()~="") then
			 whosebiggest = LootDeciderPlayer:GetText();
			 biggest = tonumber(LootDeciderAmount:GetText());
		end

	end
	local found, _, itemString, itemName = string.find(ItemLinkText:GetText(), "^|c%x+|Hitem:(%d+).+|h%[(.+)%]");

	whosebiggest = DKPMS:Trim(whosebiggest);
	whosebiggest = tonumber(DKPMS:Trim(biggest));

	LootDeciderGiveLoot:Enable();

	if(biggest == 0) then
		SendChatMessage("No bids received on "..ItemLinkText:GetText()..". Going to dusting.", "RAID", nil, nil);

		DKPMS:AddToHistory("Disenchant","0",time(),itemString,itemName);

		LootDeciderGiveLoot:Disable();


		for i = 1, 6 do
			getglobal("RowEntry"..i.."StartButton"):Enable();
		end

   else
		whosebiggest = LootDeciderPlayer:GetText();
		biggest = LootDeciderAmount:GetText();

		SendChatMessage(whosebiggest.." has won "..ItemLinkText:GetText().." for " .. biggest .." DKP!", "RAID", nil, nil);

		DKPMS:ChangeValue(whosebiggest,"-"..biggest);


		DKPMS:AddToHistory(whosebiggest,biggest,time(),itemString,itemName);

		if(zLootWindow:IsVisible()) then
			  getglobal("RowEntry"..LootDeciderLootWindowID:GetText().."StartButtonText"):SetText(whosebiggest);

			for i = 1, 6 do
				getglobal("RowEntry"..i.."StartButton"):Enable();
			end
		end
   end
end

function StartBidding(LootID,framename,id)

	if(ItemLinkText:GetText()~=getglobal("RowEntry"..id.."TooltipID"):GetText()) then --new loot
		ItemLinkText:SetText(getglobal("RowEntry"..id.."TooltipID"):GetText());
		LootDeciderLootID:SetText(LootID);
		LootDeciderLootWindowID:SetText(id);

		LootDeciderPlayer:SetText("");
		LootDeciderAmount:SetText("");

		LootDeciderStartTimer:Enable();
		LootDeciderStopTimer:Disable();
		LootDeciderAccept:Disable();
		LootDeciderGiveLoot:Disable();
	end



	for i = 1, 6 do
		if(i~=id) then
		getglobal("RowEntry"..i.."StartButton"):Disable();
		else
		getglobal("RowEntry"..i.."StartButton"):Enable();
		end
	end

		DKPMSld:LootDecider_Toggle();

end


function DKPMSld:AnnounceLoot()

	local list = true;
	local i = 1;

	local output = "";

	while (list==true and i<=6) do
		if(getglobal("RowEntry"..i):IsVisible()) then

			output = output..getglobal("RowEntry"..i.."TooltipID"):GetText();
			if(mod(i,3)==0) then
				SendChatMessage(output, "RAID", nil, nil);
				output = "";
			end

			i=i+1;

		else
			list=false;
		end
	end 
	SendChatMessage(output, "RAID", nil, nil);
end



function DKPMSld:GiveLoot(player)
	if(LootFrame:IsVisible()) then
		local lootIcon, lootName, lootQuantity, rarity= GetLootSlotInfo(GetNumLootItems());
		local ci = 1
		for ci = 1, GetNumRaidMembers() do
			if (GetMasterLootCandidate(ci) == player) then
				for id = 1, GetNumLootItems() do
					if (getglobal("ItemLinkText"):GetText() == GetLootSlotLink(id)) then    
						local dialog = StaticPopup_Show ("GiveLoot_WARNING", GetLootSlotLink(id),player);
						argsToDialog = {id,ci}; --id: lootnr, ci: playerID;						
						if(dialog) then
							dialog.data = argsToDialog;     -- pass the info to add to the dialog
						end					   
					end       
				end   							
			end
		end
	else
		DKPMS:Print("Cannot give loot. Loot Window not open");
	end
end
